package 剑指offer;

import java.util.Collections;
import java.util.PriorityQueue;

public class _40最小的k个数 {
    // topK
    public int[] getLeastNumbers(int[] arr, int k) {
        int[] result = new int[k];
        if (arr.length == 0 || k <= 0 || k > arr.length){
            return result;
        }
        //优先级队列                                        初始化容量，排序规则     自然排序的相反
        PriorityQueue<Integer> queue = new PriorityQueue<>(k, Collections.reverseOrder());
        for (int i = 0; i < arr.length; i++) {
            if(i < k){
                queue.offer(arr[i]);
            }else {
                if(arr[i] < queue.peek()){
                    queue.poll();
                    queue.offer(arr[i]);
                }
            }
        }
        for (int i = 0; i < k; i++) {
            result[i] = queue.poll();
        }
        return result;
    }
}
